import React, {useState,useEffect} from "react";
import {get, trim} from "lodash";
import {Modal, Form, Input, Checkbox, Button, Col} from "antd/lib";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import {UserProfile} from "@/components/proptypes";
import notification from "@/services/notification";
import {currentUser} from "@/services/auth";
import GlobalSetting from "@/services/globalsetting";
import Enums from "@/services/enums";
import Customer from "@/services/customer";
function CreateGlobalSettingDialog({ globalsetting, dialog }) {
  //const {optionsLoaded, options } = useQueryEnumsItems('contract_enum');
  const [dataLoaded, setDataLoaded] = useState(globalsetting.id ===0 ? true : false);
  const [code, setCode] = useState("");
  const [value, setvalue] = useState("");
  const [type, settype] = useState("");
  const [message, setmessage] = useState("");
  const [consult, setconsult] = useState("");
  const [consult2, setconsult2] = useState("");
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateGlobalSettingEnabled = useState(true);//policy.isAdmin() || policy.isDefault();

  useEffect(() => {
    if (globalsetting.id === 0) return;
    setCode(globalsetting.code);
    settype(globalsetting.type);
    setvalue(globalsetting.value);
    setmessage(globalsetting.message);
    setDataLoaded(true);
    if(globalsetting.type==="合同页面" && globalsetting.code==="预算控制" && consult===""){
      Enums.items("contract_enum").then(data => {
        let valuses='';
        data.forEach((item) => {
          if(item.children.length>0){
            item.children.forEach((item2) => {
              // valuses=item2.children;
              // valuses =item.label;
              // valuses =test;
              if(item2.children !== undefined){
                item2.children.forEach((item3) => {
                  valuses =valuses +'(编码:'+item3.key+',名称:'+item.label +'/'+item2.label+'/'+item3.label+')';
                });
              }else{
                valuses =valuses +'(编码:'+item2.key+',名称:'+item.label +'/'+item2.label+')';
              }
            });
          }else{
          valuses =valuses +'(编码:'+item.key+',名称:'+item.label+')';
        }
        });
        setconsult('合同类别：'+valuses);
      }).catch(error => {
      });
      let params={
        code: "",
        name: "",
        userid: currentUser.id,
      }
      Customer.querydepartment(params).then(data => {
        let valuses='';
        data.forEach((item) => {
          valuses =valuses +'(id:'+item.id+',名称:'+item.name+')';
        });
        setconsult2('部门：'+valuses);
      }).catch(error => {
      });
    }
  }, [globalsetting]);

  function handlevalueChange(event) {
    const value = trim(event.target.value);
    setvalue(value);
    setIsValid(value !== "");
  }

  function handleSubmit() {
    setSaveInProgress(true);
   let data={id: globalsetting.id,//
            userid: currentUser.id,//--操作员ID
            code: code,
            value: value,
            type: type,
            message: message }
      GlobalSetting.save(data)
        .then(() => {
          dialog.close({ success: true});
        })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
          setSaveInProgress(false);
        });
  }

  return (
    <Modal
      {...dialog.props}
      {...(isCreateGlobalSettingEnabled ? {} : { footer: null })}
      title="全局变量管理"
      width={document.querySelector('body').offsetWidth*0.6}
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
      <DynamicComponent name="CreateGlobalSettingDialogExtra" disabled={!isCreateGlobalSettingEnabled}>
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
        <Form.Item style={{ marginBottom: 5 }} label="模块">
        <Input
          defaultValue={type}
          placeholder="模块"
          disabled={true}
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="设置内容">
        <Input
          defaultValue={code}
          placeholder="设置内容"
          disabled={true}
          autoFocus
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="值">
        <textarea
          rows="3" 
          value={value}
          cols={document.querySelector('body').offsetWidth*0.5/12}
          textAlignVertical="top"
          onChange={handlevalueChange}
          placeholder="值"
          disabled={saveInProgress}
          autoFocus
        />
        </Form.Item>
        <Form.Item style={{ marginBottom: 5 }} label="说明">
          <textarea
            rows="3" 
            cols={document.querySelector('body').offsetWidth*0.5/12}
            textAlignVertical="top"
            height="100px"
            value={message}
            placeholder="说明"
            disabled={true}
          />
        </Form.Item>
        {consult !=="" && (<Form.Item style={{ marginBottom: 5 }} label="备注">
          <textarea
            rows="8" 
            cols={document.querySelector('body').offsetWidth*0.5/12}
            textAlignVertical="top"
            height="100px"
            value={consult + consult2}
            placeholder="备注"
            disabled={true}
          />
        </Form.Item>)}
      </Form>
      </DynamicComponent>
      )}
    </Modal>
  );
}

CreateGlobalSettingDialog.propTypes = {
  GlobalSetting: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateGlobalSettingDialog);
